import { ChangeDetectionStrategy, Component, Input, NgZone, ChangeDetectorRef, ElementRef } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: 'repair-china',
  templateUrl: './repair-china.component.html',
  styleUrls: ['./repair-china.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.card]': 'true',
  },
})
export class RepairChinaComponent {
  @Input()
  set codeName(val) {
    this._codeName = val;
    this.attachData(this._codeName);
  }
  _codeName = null;

  @Input()
  title = null;
  data = [];
  time = null;
  loading = true;
  noData = true;
  chart = null;

  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  render(er: ElementRef) {
    this.ngZone.runOutsideAngular(() => setTimeout(() => this.init(er.nativeElement), 50));
  }

  private attachData(codeName) {
    const { ngZone } = this;
    ngZone.run(() => {
      this.loading = true;
      this.cdr.detectChanges();
    });
    this.noData = true;
    this.data = [];
    this.http.get(`/cf/report/prod/repairchina/${codeName}`).subscribe((res: any) => {
      ngZone.run(() => {
        if (res.data && res.data.length > 0) {
          this.noData = false;
          this.data = res.data;
        }
        this.time = new Date();
        this.loading = false;
        this.cdr.detectChanges();
      });
    });
  }

  private init(container: HTMLElement) {
    const { data } = this;
    this.http
      .get(`https://gw.alipayobjects.com/os/antvdemo/assets/data/china-provinces.geo.json`)
      .subscribe(GeoJSON => {
        const userData = [];
        const geoDv = new DataSet.View()
          .source(GeoJSON, {
            type: 'GeoJSON',
          })
          .transform({
            type: 'map',
            callback: function callback(row) {
              let v = 0;
              const tmp = data.filter(r => row.name.startsWith(r.PROVINCE));
              if (tmp.length !== 0) {
                v = tmp[0].COUNT;
              }
              userData.push({
                longitude: row.centroidX,
                latitude: row.centroidY,
                name: row.name,
                value: v,
              });
              return row;
            },
          });
        const chart = (this.chart = new G2.Chart({
          container,
          forceFit: true,
          height: 500,
          padding: 'auto',
        }));

        chart.scale({
          latitude: {
            sync: true,
            nice: false,
          },
          longitude: {
            sync: true,
            nice: false,
          },
        });
        chart.legend(false);
        chart.axis(false);
        chart.tooltip(true, {
          showTitle: false,
          itemTpl: '<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>',
        });

        const geoView = chart.view();
        geoView.source(geoDv);
        geoView
          .polygon()
          .position('longitude*latitude')
          .color('grey')
          .label('name', {
            offset: 0,
          });

        const userView = chart.view();
        userView.source(userData);
        userView
          .heatmap()
          .position('longitude*latitude')
          .color('value', '#F51D27-#FA541C-#FF8C12-#FFC838-#FAFFA8-#80FF73-#12CCCC-#1890FF-#6E32C2')
          .size(window.innerHeight / 20)
          .style({
            blur: window.innerHeight / 15,
          })
          .tooltip('name*value', (name, value) => {
            return {
              name,
              value,
            };
          });
        chart.render();
        this.cdr.detectChanges();
      });
  }
}
